package com.infore.airsupervise.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.SearchAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.EventE;
import com.infore.airsupervise.biz.impl.EventBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.AutoEventFragment;
import com.infore.airsupervise.ui.widget.CommolySearchView;
import com.yanzhenjie.loading.LoadingView;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017/8/4.
 */

public class SearchDataRateActivity extends BaseActivity {

    @BindView(R.id.search_RecyclerView)
    SwipeMenuRecyclerView mRecyclerView;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_searchClean)
    ImageView ivSearchClean;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.search_empty_view)
    View SearchEmptyVview;
    @BindView(R.id.search_layout_view)
    LinearLayout mSearchLayoutVview;

    private SearchAdapter adapter;
    private List<EventE> mDatas=new ArrayList<>();
    private EventBizImpl eventBiz;
    private int loadmore=0;
    private boolean firstLoadData=false;
    private SweetAlertDialog dialog;
    private LinearLayout layout;
    private int dataType ; //事件类型标识； 自动0 手动1


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchdatarate);
        ButterKnife.bind(this);
        eventBiz = new EventBizImpl();
        Intent it = getIntent();
        if(it != null){
            dataType = it.getIntExtra(Constants.INTENT_INT_KEY,0);
        }
        initSearchView();
    }

    /**
     * 初始化控件
     */
    private void initSearchView() {

        etSearch .setFocusableInTouchMode(true);
        etSearch.requestFocus();
        InputMethodManager inputManager =
                (InputMethodManager)etSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(etSearch, 0);

        mRecyclerView.setSwipeItemClickListener(mItemClickListener);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        mRecyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 自定义的核心就是DefineLoadMoreView类。
        DefineLoadMoreView loadMoreView = new DefineLoadMoreView(this);
        mRecyclerView.addFooterView(loadMoreView); // 添加为Footer。
        mRecyclerView.setLoadMoreView(loadMoreView); // 设置LoadMoreView更新监听。
        mRecyclerView.setLoadMoreListener(mLoadMoreListener);
        adapter = new SearchAdapter(mDatas);
        mRecyclerView.setAdapter(adapter);
        layout = (LinearLayout) findViewById(R.id.search_layout);
        mSearchLayoutVview.setVisibility(View.GONE);
        SearchEmptyVview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    if(etSearch.getText().toString()!=null&&!etSearch.getText().toString().equals("")){
                        layout.setBackgroundColor(getResources().getColor(R.color.backgroud_white));
                        SearchEmptyVview.setVisibility(View.GONE);
                        mSearchLayoutVview.setVisibility(View.VISIBLE);
                        SearchResult(etSearch.getText().toString());

                    }
                    return true;
                }
                return false;
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() > 0 && !s.toString().equals("")) {
                    ivSearchClean.setVisibility(View.VISIBLE);
                } else {
                    ivSearchClean.setVisibility(View.INVISIBLE);
                    mDatas.clear();
                    adapter.notifyDataSetChanged();
                    loadmore=0;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }


    public void SearchResult(String keyword){
        //loading dialog

        if(!firstLoadData){
            dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                   .setTitleText(MsgConst.HARD_LOADING)
                   .setContentText(MsgConst.PLEASE_WAITING);
            dialog.setCancelable(false);
            dialog.show();
            firstLoadData=true;
        }
        if(dataType == -1){
            //事件处理搜索
            eventBiz.getSearchHandleEventList(keyword,loadmore,onResponseListener);
        }else {
            //事件搜索
            eventBiz.getSearchEventList(keyword, dataType, loadmore, onResponseListener);
        }
    }

    /**
     * 网络请求回调方法
     */
    private OnServerResponseListener<List<EventE>> onResponseListener = new OnServerResponseListener<List<EventE>>() {
        @Override
        public void onSucceed(List<EventE> result, String desc) {
            mDatas.addAll(result);
            adapter.notifyDataSetChanged();
            //


            if(result.size()==0){
                mRecyclerView.loadMoreFinish(false, false);
            }
            mRecyclerView.loadMoreFinish(false, true);
            if(dialog!=null){
                dialog.dismiss();
            }
            loadmore++;
        }

        @Override
        public void onFailed(int errorCode, String title, String desc) {

            //dialog 错误 异常提示
            if(dialog==null){
                dialog = new SweetAlertDialog(SearchDataRateActivity.this,SweetAlertDialog.WARNING_TYPE)
                        .setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE);
                dialog.setCancelable(false);
                dialog.show();
            }else{
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }



        }
    };

    /**
     * 上拉加载更多
     */

    private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            SearchResult(etSearch.getText().toString());

        }
    };







    /**
     * Item点击监听。
     */
    SwipeItemClickListener mItemClickListener = new SwipeItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {

            EventE eventE = mDatas.get(position);
            if (eventE != null) {
                // JumpUtil.jumpFromTo(getActivity(), EventDetailsActivity.class, "eventid", eventE.getId());
                Intent intent = new Intent(SearchDataRateActivity.this, EventDetailsActivity.class);
                intent.putExtra("eventid", eventE.getId());
                intent.putExtra("flag", eventE.getFlag());
                startActivity(intent);
            }
          //  Toast.makeText(SearchDataRateActivity.this, "第" + position + "个", Toast.LENGTH_SHORT).show();
        }
    };


    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.dp_50);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            SwipeMenuItem deleteItem = new SwipeMenuItem(SearchDataRateActivity.this)
                    .setBackground(R.drawable.selector_red)
                    .setText("删除")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);


            SwipeMenuItem addItem = new SwipeMenuItem(SearchDataRateActivity.this)
                    .setBackground(R.drawable.selector_green)
                    .setText("编辑")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);


            switch (viewType) {
                case 1:
                    swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。
                    swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
                    break;
                case 2:
                    //  swipeRightMenu.addMenuItem(null);
                    //当不可编辑的时候 什么都不需要做就可以了
                    break;
            }
        }
    };


    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                Toast.makeText(SearchDataRateActivity.this, "list第" + adapterPosition + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
                Toast.makeText(SearchDataRateActivity.this, "list第" + adapterPosition + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
            }
        }
    };


    /**
     * 返回 或关闭
     */
    @OnClick(R.id.tv_search)
    void ReturnBtun() {

        finish();

    }

    @OnClick(R.id.iv_searchClean)
    void cleanText() {

        etSearch.setText("");
        loadmore=0;
        ivSearchClean.setVisibility(View.INVISIBLE);

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        View v = getCurrentFocus();
        hideKeyboard(ev,v,this);
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 点击空白处隐藏键盘
     *
     * @param
     * @return
     */


   // @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            View v = getCurrentFocus();
//            if (isShouldHideInput(v, ev)) {
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                if (imm != null) {
//                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//                    finish();
//                }
//            }
//            return super.dispatchTouchEvent(ev);
//        }
//        // 必不可少，否则所有的组件都不会有TouchEvent了
//        if (getWindow().superDispatchTouchEvent(ev)) {
//            return true;
//        }
//        return super.dispatchTouchEvent(ev);
//    }
//
//    public boolean isShouldHideInput(View v, MotionEvent event) {
//        if (v != null && (v instanceof EditText)) {
//            int[] leftTop = {0, 0};
//            // 获取输入框当前的location位置
//            v.getLocationInWindow(leftTop);
//            int left = leftTop[0];
//            int top = leftTop[1];
//            int bottom = top + v.getHeight();
//            int right = left + v.getWidth();
//            if (event.getX() > left && event.getX() < right
//                    && event.getY() > top && event.getY() < bottom) {
//                // 点击的是输入框区域，保留点击EditText的事件
//                return false;
//            } else {
//                return true;
//            }
//        }
//        return false;
//    }

    public  void hideKeyboard(MotionEvent event, View view,
                                    Activity activity) {
        try {
            if (view != null && view instanceof EditText) {
                int[] location = { 0, 0 };
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left
                        + view.getWidth(), bootom = top + view.getHeight();
                // 判断焦点位置坐标是否在空间内，如果位置在控件外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right
                        || event.getY() < top || event.getRawY() > bootom) {
                    // 隐藏键盘
                    IBinder token = view.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(token,
                            InputMethodManager.HIDE_NOT_ALWAYS);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 这是这个类的主角，如何自定义LoadMoreView。
     */
    static final class DefineLoadMoreView extends LinearLayout implements SwipeMenuRecyclerView.LoadMoreView, View.OnClickListener {

        private LoadingView mLoadingView;
        private TextView mTvMessage;

        private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener;

        public DefineLoadMoreView(Context context) {
            super(context);
            setLayoutParams(new ViewGroup.LayoutParams(-1, -2));
            setGravity(Gravity.CENTER);
            setVisibility(GONE);

            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

            int minHeight = (int) (displayMetrics.density * 10 + 0.5);
            setMinimumHeight(minHeight);

            inflate(context, R.layout.layout_fotter_loadmore, this);
            mLoadingView = (LoadingView) findViewById(R.id.loading_view);
            mTvMessage = (TextView) findViewById(R.id.tv_message);

            int color1 = ContextCompat.getColor(getContext(), R.color.google_red);
//            int color2 = ContextCompat.getColor(getContext(), R.color.google_red);
//            int color3 = ContextCompat.getColor(getContext(), R.color.google_red);

            mLoadingView.setCircleColors(color1, color1, color1);
            setOnClickListener(this);
        }

        /**
         * 马上开始回调加载更多了，这里应该显示进度条。
         */
        @Override
        public void onLoading() {
            setVisibility(VISIBLE);
            mLoadingView.setVisibility(VISIBLE);
            mTvMessage.setVisibility(VISIBLE);
            mTvMessage.setText("正在努力加载，请稍后");
        }

        /**
         * 加载更多完成了。
         *
         * @param dataEmpty 是否请求到空数据。
         * @param hasMore   是否还有更多数据等待请求。
         */
        @Override
        public void onLoadFinish(boolean dataEmpty, boolean hasMore) {
            if (!hasMore) {
                setVisibility(VISIBLE);

                if (dataEmpty) {
                    mLoadingView.setVisibility(GONE);
                    mTvMessage.setVisibility(VISIBLE);
                    mTvMessage.setText("暂时没有数据");
                } else {
                    mLoadingView.setVisibility(GONE);
                    mTvMessage.setVisibility(VISIBLE);
                    mTvMessage.setText("没有更多数据啦");
                }
            } else {
                setVisibility(INVISIBLE);
            }
        }

        /**
         * 调用了setAutoLoadMore(false)后，在需要加载更多的时候，这个方法会被调用，并传入加载更多的listener。
         */
        @Override
        public void onWaitToLoadMore(SwipeMenuRecyclerView.LoadMoreListener loadMoreListener) {
            this.mLoadMoreListener = loadMoreListener;

            setVisibility(VISIBLE);
            mLoadingView.setVisibility(GONE);
            mTvMessage.setVisibility(VISIBLE);
            mTvMessage.setText("点我加载更多");
        }

        /**
         * 加载出错啦，下面的错误码和错误信息二选一。
         *
         * @param errorCode    错误码。
         * @param errorMessage 错误信息。
         */
        @Override
        public void onLoadError(int errorCode, String errorMessage) {
            setVisibility(VISIBLE);
            mLoadingView.setVisibility(GONE);
            mTvMessage.setVisibility(VISIBLE);

            // 这里要不直接设置错误信息，要不根据errorCode动态设置错误数据。
            mTvMessage.setText(errorMessage);
        }

        /**
         * 非自动加载更多时mLoadMoreListener才不为空。
         */
        @Override
        public void onClick(View v) {
            if (mLoadMoreListener != null) mLoadMoreListener.onLoadMore();
        }
    }
}
